package com.chen.common;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import lombok.SneakyThrows;

/**
 * @Description 获取本地的mac地址
 * @Author Pengwei
 * @CreatDate 2021/11/16 22:34
 */
public class LocalUtils {

    @SneakyThrows
    private static String getLocalMac(InetAddress ia) {
        //获取网卡，获取地址
        byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
        if (mac == null || mac.length == 0) {
            return null;
        }
        StringBuffer sb = new StringBuffer("");
        for (int i = 0; i < mac.length; i++) {
            if (i != 0) {
                sb.append("-");
            }
            //字节转换为整数
            int temp = mac[i] & 0xff;
            String str = Integer.toHexString(temp);
            if (str.length() == 1) {
                sb.append("0" + str);
            } else {
                sb.append(str);
            }
        }
        return sb.toString().toUpperCase();
    }

    /**
     * 获取本地的所有IP地址
     * @return
     */
    @SneakyThrows
    public static List<String> getLocalIPs() {
        List<String> macIPs = new ArrayList();
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface networkInterface = networkInterfaces.nextElement();
            Enumeration<InetAddress> addressEnumeration = networkInterface.getInetAddresses();
            while (addressEnumeration.hasMoreElements()) {
                InetAddress inetAddress = addressEnumeration.nextElement();
                if (inetAddress != null && inetAddress instanceof Inet4Address) { // IPV4
                    String hostAddress = inetAddress.getHostAddress();
                    macIPs.add(hostAddress);
                }
            }
        }
        return macIPs;
    }
}
